<template>
    <div>
        <BasicModal @register="register" :title="title" width="800px" :destroyOnClose="true" :canFullscreen="false"
            :showOkBtn="false" :showCancelBtn="false">
            <BasicForm @register="registerForm">
                <template #logoUrl="{ model, field }">
                    <ClipUploadImg v-model="model[field]" />
                </template>
            </BasicForm>
        </BasicModal>



    </div>
</template>
    
<script lang="ts" setup>
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, FormSchema, useForm, } from '@/components/Form';
import { ref } from 'vue';
import { useMessage } from '@/hooks/web/useMessage';
import { getInstitutionList, getOpenShopDetail, saveShop, updateShop } from '@/api/hby/merchantPlatform';
import { ClipUploadImg } from '@/components/Upload/index';
import { ShopStatus } from '@/enums/merchantPlatformEnum';
import { IOpenShop, IShopInfo, InstitutionList } from '@/api/hby/merchantPlatform/type';
import { isArray } from '@/utils/is';

const title = ref('开通商户平台');
const { createMessage } = useMessage();
const type = ref(1);
const emit = defineEmits(['reload', 'register']);


const tenantId = ref();
const institutionList = ref<InstitutionList[]>();
const formData = ref<IOpenShop>();
const btn = ref(false);

const schemas: FormSchema[] =
    [
        {
            field: 'tenantId',
            component: 'ApiSelect',
            label: '机构名称：',
            dynamicDisabled: false,
            rules: [{
                validateTrigger: ['change'], required: true, validator(_rule, value) {
                    if (!value) return Promise.reject('请输入机构名称');
                    clearValidate('tenantId');
                    return Promise.resolve();
                },
            }],
            componentProps: () => {
                return {
                    onChange: (value: number) => {
                        if (type.value == 2) return;
                        const institution = institutionList.value?.find(item => item.tenantId == value);
                        setFieldsValue({
                            name: institution?.orgName,
                            logoUrl: institution?.logo,
                            subName: institution?.orgName
                        })
                    },
                    placeholder: '请选择机构',
                    api: async (params) => {
                        const res = await getInstitutionList(params);
                        institutionList.value = res;
                        return res.map(item => {
                            item.allName = item.orgName;
                            if (item.isOpenMall > 0 && item.tenantId != tenantId.value) {
                                item.disabled = true;
                                item.allName = item.orgName + ' ' + '已开通'
                            }
                            return item;
                        })
                    },
                    labelField: 'allName',
                    valueField: 'tenantId',
                    showSearch: true,
                    filterOption: (input: string, option: any) => {
                        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                    },
                }
            },
            colProps: {
                span: 24,
            },
        },
        {
            field: 'name',
            component: 'Input',
            rules: [{
                validateTrigger: ['change'], required: true, validator(_rule, value) {
                    if (!value) return Promise.reject('请填写商户平台名称');
                    clearValidate('name');
                    return Promise.resolve();
                },
            }],
            label: '组织名称：',
            componentProps: {
                maxlength: 20,
                placeholder: '请填写商户平台名称',
            },
            colProps: {
                span: 24,
            },
        },
        {
            field: 'subName',
            component: 'Input',
            rules: [{
                validateTrigger: ['change'], required: true, validator(_rule, value) {
                    if (!value) return Promise.reject('请填写平台名称');
                    clearValidate('subName');
                    return Promise.resolve();
                },
            }],
            label: '平台名称',
            componentProps: {
                maxlength: 20,
                placeholder: '请填写平台名称',
            },
            colProps: {
                span: 24,
            },
        },
        {
            field: 'logoUrl',
            component: 'Upload',
            slot: 'logoUrl',
            label: '商户平台LOGO：',
            colProps: {
                span: 24,
            },
        },
        {
            field: 'status',
            component: 'Switch',
            label: '启用状态',
            defaultValue: ShopStatus.YES,
            show: false,
            componentProps: {
                checkedValue: ShopStatus.YES,
                unCheckedValue: ShopStatus.NO,
            },
            colProps: {
                span: 24,
            },
        },
        {
            field: 'remark',
            component: 'InputTextArea',
            label: '备注',
            colProps: {
                span: 24,
            },
        },
    ]




const [registerForm, { setProps, setFieldsValue, validate, clearValidate, updateSchema }] = useForm({
    schemas: schemas,
    autoFocusFirstItem: true,

    actionColOptions: {
        span: 24,
    },
    labelWidth: 140,
    baseColProps: { span: 18 },
    submitButtonOptions: {
        text: '确定',
    },
    resetButtonOptions: {
        text: '取消',
    }
    ,
    submitFunc: async () => {
        try {
            btn.value = true;
            const res: IOpenShop = await validate();
            setProps({
                submitButtonOptions: {
                    loading: true,
                },
            });
            const dataForm: IOpenShop = { ...res }
            if (isArray(dataForm.logoUrl)) {
                dataForm.logoUrl = dataForm.logoUrl[0];
            }
            if (type.value == 1) {
                await saveShop(dataForm)
                createMessage.success('开通成功！');
            } else {
                await updateShop(dataForm)
                createMessage.success('修改成功！');
            }

            emit('reload');
            closeModal();
        } catch (error) {
            console.error(error);

        } finally {
            btn.value = false;
            setProps({
                submitButtonOptions: {
                    loading: false,
                },
            });
        }
    },
    resetFunc: async function () {
        closeModal();
    }
});

const [register, { closeModal }] = useModalInner(async (data: { type: number, row: IShopInfo }) => {
    type.value = data.type
    title.value = data.type == 1 ? '开通商户平台' : '编辑商户平台';
    schemas[0].dynamicDisabled = false;
    updateSchema(schemas);
    if (data.type == 1) return;
    schemas[0].dynamicDisabled = true;
    updateSchema(schemas);
    tenantId.value = data.row.tenantId;
    const res = await getOpenShopDetail(data.row.tenantId);
    formData.value = res;
    setFieldsValue(res);
});
</script>
    
<style lang="less" scoped></style>
    